package alik.notes.server;

import java.util.List;

import alik.loginservice.shared.exception.NotLoggedInException;
import alik.notes.server.persistence.NotesPersistence;
import alik.notes.shared.data.Note;
import alik.notes.shared.service.NotesService;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
public class NotesServiceImpl extends RemoteServiceServlet implements NotesService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 9129964825493119441L;

	public List<Note> getNotes() throws NotLoggedInException {
		checkLoggedIn();

		List<Note> notes = NotesPersistence.queryNotes(getUser().getUserId());
		return notes;
	}

	@Override
	public void addNote(Note note) throws NotLoggedInException {
		checkLoggedIn();
		NotesPersistence.addNote(note, getUser().getUserId());
	}

	private void checkLoggedIn() throws NotLoggedInException {
		if (getUser() == null) {
			throw new NotLoggedInException("User not logged in.");
		}
	}

	private User getUser() {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		return user;
	}

}
